package ru.nsu.ccfit.kalah.game;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class GameController {
    Player southPlayer;
    Player northPlayer;
    Player currentPlayer;
    Field field = new Field();
    KalahController kalahController = new KalahController(field);
    MoveAnimatorListener moveAnimatorListener;

    public void setMoveAnimatorListener(MoveAnimatorListener moveAnimatorListener) {
        this.moveAnimatorListener = moveAnimatorListener;
    }

    public GameController(Player southPlayer, Player northPlayer) {
        this.southPlayer = southPlayer;
        this.northPlayer = northPlayer;

        southPlayer.init(this);
        northPlayer.init(this);
    }

    public boolean isFirstPlayer() {
        return kalahController.currentPlayer == PlayerType.SOUTH;
    }

    public void startGame() {
        currentPlayer = southPlayer;
        currentPlayer.requestMove();
    }
    EndOfGameListener endOfGameListener;

    public void setEndOfGameListener(EndOfGameListener endOfGameListener) {
        this.endOfGameListener = endOfGameListener;
    }

    RequestMoveCallback callback = new RequestMoveCallback() {
        @Override
        public void request() {
            currentPlayer = kalahController.currentPlayer == PlayerType.SOUTH ? southPlayer : northPlayer;

              if(kalahController.terminal()) {
                 // todo animation of end of the game (move to players pits)

                 if(endOfGameListener!=null) {
                     endOfGameListener.onGameEnded(kalahController.getFirst(), kalahController.getSecond());
                 }
                  return;
              }

            ready = true;
            currentPlayer.requestMove();
        }
    };
    boolean ready = true;

    public boolean isReady() {
        return ready;
    }

    /**
     * @param index from 0 to 6   for all players
     */
    public void makeMove(int index) {
        Log.e("xxx", "makeMove = " + index);
        if (ready) {
            if (kalahController.allow(index)) {

                ready = false;
                if (moveAnimatorListener != null) {
                    List<AbstractMoveAnimation> animations = new ArrayList<AbstractMoveAnimation>();

                    kalahController.moveWithAnimation(index, animations);
                    moveAnimatorListener.animate(animations, callback);
                } else {
                    // if no animation, do simple move

                    kalahController.move(index);
                    currentPlayer = kalahController.currentPlayer == PlayerType.SOUTH ? southPlayer : northPlayer;
                    currentPlayer.requestMove();
                }

            } else {
                currentPlayer.requestMove();
            }
        }

    }


    public Field getField() {
        return field;
    }
}
